package com.uyayo.framework.limiter.utils;

import com.google.common.base.Strings;
import com.uyayo.framework.limiter.constants.CharacterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/***
 * 请求数据
 *
 * @author hfj
 * @date: 2018/8/13
 * @since: 1.0
 */
public class RequestUtils {
    private static final Logger log = LoggerFactory.getLogger(RequestUtils.class);
    private static final String[] PROXY_REMOTE_IP_ADDRESS = {"X-Real-IP", "x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP"};

	/**
     * 获取用户真实IP
     *
     * @param request request请求
     * @return String IP
     */
    public static String getIpAddr(HttpServletRequest request) {
        for (String headerKey : PROXY_REMOTE_IP_ADDRESS) {
            String header = request.getHeader(headerKey);
            if (!Strings.isNullOrEmpty(header) &&
                    !CharacterConstants.UNKNOWN_STRING.equalsIgnoreCase(header)) {
                String[] strings = header.split(",");
                for (String string : strings) {
                    String value = string.trim();
                    if (!Strings.isNullOrEmpty(value) &&
                            !CharacterConstants.UNKNOWN_STRING.equalsIgnoreCase(value)) {
                        return value;
                    }
                }
            }
        }
        return request.getRemoteAddr().trim();
    }
}
